package com.joker.cart.service.Task;

import com.joker.cart.mapper.CartItemMapper;
import com.joker.cart.vo.CartItemVo;
import com.joker.common.redis.service.RedisService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Component
public class RedisSyncTask {
    @Resource
    private RedisService redisService;
    @Resource
    private CartItemMapper cartItemMapper;



    private static final String CART_KEY = "cart:";
    //定时同步
    // 每五分钟执行一次
    @Scheduled(cron = "0 */5 * * * *")
    public void sync() {
        Collection<String> keys = redisService.keys(CART_KEY + "*");

        //判断redis中是否有证据
        if (keys.size()==0){
            cartItemMapper.delectCartItem();
        }

        keys.forEach(key -> {
            Map<String, CartItemVo> map = redisService.getCacheMap(key);

            List<CartItemVo> cartItemVoList =cartItemMapper.selectCartItem();

            //判断数据库是否为空
            if (cartItemVoList.size()!=0){
                cartItemMapper.delectCartItem();
            }

            map.forEach((k,v)->{
                cartItemMapper.addCartItem(v);
            });

        });

    }
}
